package com.base.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${loginPath:/html/page/login}")
    private String loginPath;

    private static final Logger LOGGER= LoggerFactory.getLogger(UserInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            LOGGER.info("没有映射到方法，则无需检查直接通过");
            return true;
        }
        HandlerMethod heHandlerMethod = (HandlerMethod)handler;
        Method method = heHandlerMethod.getMethod();
        //判断接口是否需要登录
//        LoginRequired loginRequired=method.getAnnotation(LoginRequired.class);
//        //有LoginRequired注解，不需要认证
//        if(loginRequired!=null){
//            return true;
//        }
        //从header中获取token
        String token = request.getHeader("token");
        if (token!=null) {
            //判断redis中token是否失效
            boolean falg = redisTemplate.hasKey(token);
            if (falg) {
                return true;
            }
        }

        //登录状态检查,使用response返回给前端指定信息
        setHeader(request, response, "{\r\n" +
                "    \"code\": \"-1\",\r\n" +
                "    \"message\": \"请进行登录！\",\r\n" +
                "    \"data\": \"null\"\r\n" +
                "}");
        response.sendRedirect(request.getContextPath()+loginPath);
        return false;
    }

    /**
     * response设置header，实现跨域
     * @param request
     * @param response
     * @param message	返回给前端的消息，json格式
     */
    @SuppressWarnings("unused")
    private void setHeader(HttpServletRequest request,HttpServletResponse response,String message){
        try {
            //跨域的header设置
            response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", request.getMethod());
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            //防止乱码，适用于传输JSON数据
            response.setHeader("Content-Type","application/json;charset=UTF-8");
            response.getWriter().write(message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
